﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using Elmah;
using Viettel.VOFFICE.DAO.Models;
using Viettel.VOFFICE.Web.Helpers;
using Viettel.VOFFICE.Web.Models;
using Viettel.VOFFICE.util;
namespace Viettel.VOFFICE.Web.Controllers
{
    [AttributeHelper("OfficePartnerController_ControllerName")]
    public class OfficePartnerController : BaseController
    {
        [HttpPost]
        [AttributeHelper("OfficePartnerController_AddItem")]
        [ActionName("add_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Add(OfficePartnerModel officePartner)
        {
            try
            {
                List<ValidationResult> outError;
                if (!officePartner.IsValid(out outError))
                {
                    return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                    });
                } //end ìf
                else
                {
                    var data = new OfficePartner
                    {
                        //Id = metaData.Id,
                        Name = officePartner.Name,
                        Address = officePartner.Address,
                        Email = officePartner.Email,
                        IsActive = officePartner.IsActive,
                        CreatorId = officePartner.CreatorId,
                        Phone = officePartner.Phone,
                        Representer = officePartner.Representer,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                    };
                    unitOfWork.OfficePartnerRepository.Insert(data);
                    return Json(SimplyResponse.ResposeWithId(data.Id));
                }
            }
            catch (Exception ex)
            {
                return Json(SimplyResponse.Response500());
                //throw;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        [AttributeHelper("OfficePartnerController_AddItem")]
        [ActionName("search")]
        public JsonResult Search(string key)
        {
            if (string.IsNullOrEmpty(key)) return Json(null);
            var item = unitOfWork.OfficePartnerRepository.Search(key);
            return Json(new JsonResponse()
                            {
                                Status = true,
                                Result = item.Select(o => new OfficePartnerModel(o)).ToList()
                            }, JsonRequestBehavior.AllowGet);
        }
        //search

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        [AttributeHelper("OfficePartnerController_GetAll")]
        [ActionName("get_all")]
        public JsonResult GetAll(int pageIndex = 0, int pageSize = 0)
        {
            try
            {
                if (pageIndex >= 0 && pageSize > 0)
                {
                    var list = unitOfWork.OfficePartnerRepository.Paging(pageIndex, pageSize);
                    return Json(new JsonResponse()
                    {
                        Status = true,
                        Result = new
                        {
                            PageIndex = list.PageIndex,
                            PageSize = list.PageSize,
                            PageCount = list.PageCount,
                            List = list.Select(o => new OfficePartnerModel(o))
                        }
                    }, JsonRequestBehavior.AllowGet);
                }

                else
                {
                    var list = unitOfWork.OfficePartnerRepository.Get().Select(o => new OfficePartnerModel(o));
                    return Json(new JsonResponse() { Status = true, Result = list }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                ErrorSignal.FromCurrentContext().Raise(new NotSupportedException("", ex));
                return Json(SimplyResponse.Response500(), JsonRequestBehavior.AllowGet);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [AttributeHelper("OfficePartnerController_AddItem")]
        [ActionName("delete_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult Delete(int id)
        {
            try
            {
                unitOfWork.OfficePartnerRepository.Delete(id);
                return Json(SimplyResponse.Response200());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return Json(SimplyResponse.Response200());
            }
        }
        [HttpPut]
        [ActionName("update_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult UpdateItem(OfficePartnerModel model, string modified = "all")
        {
            try
            {
                List<ValidationResult> outError;
                if (model.IsValid(out outError))
                {
                    var dboffice = unitOfWork.OfficePartnerRepository.GetById(model.Id);
                    if (dboffice == null)
                    {
                        return Json(new JsonResponse()
                                        {
                                            Status = false,
                                            Result = "Do not update item",
                                        });
                    }
                    if (modified.ToUpper().Contains("ISACTIVE"))
                    {
                        dboffice.IsActive = model.IsActive;
                    }
                    // cap nhat toan bo
                    else
                    {
                        dboffice.Id = model.Id;
                        dboffice.Name = model.Name;
                        dboffice.Address = model.Address;
                        dboffice.Email = model.Email;
                        dboffice.Phone = model.Phone;
                        dboffice.Representer = model.Representer;
                        dboffice.IsActive = model.IsActive;
                        dboffice.CreatorId = model.CreatorId;

                    }
                    //dboffice.CreatedAt = DateTime.Now;
                    dboffice.UpdatedAt = DateTime.Now;
                    unitOfWork.OfficePartnerRepository.Update(dboffice);
                    return Json(SimplyResponse.Response200());
                }
                else
                {
                    return Json(new JsonResponse()
                                    {
                                        Status = false,
                                        Result = string.Join(", ", outError.Select(o => o.ErrorMessage).ToArray())
                                    });
                }
            }
            catch (Exception)
            {
                return Json(SimplyResponse.Response500());

            }
        }
        [HttpGet]
        [ActionName("get_one_item")]
        public JsonResult GetOneItem(int id)
        {
            try
            {
                var item = unitOfWork.OfficePartnerRepository.GetById(id);
                return Json(new JsonResponse()
                                {
                                    Status = true,
                                    Result = new OfficePartnerModel(item)
                                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return Json(SimplyResponse.Response200(), JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        [ActionName("save_item")]
        [ValidateJsonAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult SaveItem(OfficePartnerModel model)
        {
            List<ValidationResult> validation;
            if (model != null && model.IsValid(out validation))
            {
                try
                {

                    var partner = new OfficePartner()
                                      {
                                          Name = model.Name,
                                          Email = model.Email,
                                          Address = model.Address,
                                          CreatedAt = DateTime.Now,
                                          UpdatedAt = DateTime.Now,
                                          IsActive = true
                                      };

                    if (model.Id > 0)
                    {
                        unitOfWork.OfficePartnerRepository.Update(partner);
                    }
                    else
                    {
                        unitOfWork.OfficePartnerRepository.Insert(partner);
                    }
                    return Json(SimplyResponse.Response200());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                    return Json(SimplyResponse.Response500());
                }
            }
            else
            {
                return Json(new JsonResponse() { Status = false, Result = "khong them mói duoc" });
            }
        }

        [HttpPost]
        [ActionName("quick_create")]
        //[ValidateAntiForgeryToken(Salt = AppConstants.TokenSalt)]
        public JsonResult QuickCreate(string name)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(name))
                {
                    return Json(new JsonResponse()
                        {
                            Status = false,
                            Result = null
                        });
                }
                var dbOfficePartner = new OfficePartner()
                    {
                        Name = name,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        CreatorId = GetCurentUserId(),
                        IsActive = true
                    };
                unitOfWork.OfficePartnerRepository.Insert(dbOfficePartner);
                return Json(new JsonResponse()
                    {
                        Status = true,
                        Result = dbOfficePartner.Id
                    });
            }
            catch (Exception)
            {
                return Json(new JsonResponse()
                    {
                        Status = false,
                        Result = null
                    });
            }
        }
    }


}

